package com.ikas.ai.server.license;

import com.ikas.ai.license.LicenseVerifyParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.FileNotFoundException;

/**
 * @author hu.bowei@ikasinfo.com
 * @date 2023-02-28- 10:58
 * @Description 在项目启动时安装证书
 */
@Component
@Slf4j
public class LicenseCheckListener implements CommandLineRunner {
    private static final String LICENSE_PATH = "license/license.lic";
    private static final String PUBLIC_CERT_PATH = "license/publicCerts.keystore";
    /**
     * 证书subject
     */
    @Value("${license.subject:ikas-poc}")
    private String subject;

    /**
     * 公钥别称
     */
    @Value("${license.publicAlias:publicCert}")
    private String publicAlias;

    /**
     * 访问公钥库的密码
     */
    @Value("${license.storePass:ikasinfo2023}")
    private String storePass;

    /**
     * 证书生成路径
     */
    @Value("${license.licensePath:}")
    private String licensePath;

    /**
     * 密钥库存储路径
     */
    @Value("${license.publicKeysStorePath:}")
    private String publicKeysStorePath;



    @Override
    public void run(String... args) throws Exception {
        try {
            licensePath = StringUtils.isBlank(licensePath) ? ResourceUtils.getFile("classpath:" + LICENSE_PATH).getPath() : licensePath;
            publicKeysStorePath = StringUtils.isBlank(publicKeysStorePath) ? ResourceUtils.getFile("classpath:" + PUBLIC_CERT_PATH).getPath() : publicKeysStorePath;
        } catch (FileNotFoundException e) {
            log.error("找不到证书路径:", e);
        }
        if(!StringUtils.isEmpty(licensePath)){
            log.info("++++++++ 开始安装证书 ++++++++");

            LicenseVerifyParam param = new LicenseVerifyParam();
            param.setSubject(subject);
            param.setPublicAlias(publicAlias);
            param.setStorePass(storePass);
            param.setLicensePath(licensePath);
            param.setPublicKeysStorePath(publicKeysStorePath);

            LicenseVerify licenseVerify = new LicenseVerify();
            //安装证书
            licenseVerify.install(param);

            log.info("++++++++ 证书安装结束 ++++++++");
        }else {
            throw new RuntimeException("++++++++ 未配置License证书 ++++++++");
        }
    }

}
